/**
 * @File   : ImageUpload.js
 * @Author : xue.xiaoBing
 * @Date   : 2020/12/18
 * @Desc   : 图片上传组件
 **/


import React, {Component} from "react";
import {PlusOutlined} from "@ant-design/icons";
import {Upload, Modal, Row, Col, Image} from "antd";

import "./ImageUpload.sass";


function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

 class ImageUpload extends Component {
  constructor(prop) {
    super(prop);
    this.state = {
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList: [],
      isChange: false
    }
  };

  handleCancel = () => {
    this.setState({
      previewVisible: false
    })
  };

  handlePreview = async file => {
    if (!file.thumbUrl && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.thumbUrl || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.thumbUrl.substring(file.thumbUrl.lastIndexOf('/') + 1),
    });
  };

  handleChange = info => {
    const fileList = [info.file];
    this.setState({
      fileList: fileList,
    });
    if(info.file.status === 'done'){
      this.setState({
        isChange:true
      })
    }
  };

  handleRemove = () => {
    this.setState({fileList: [], isChange: false})
    return false
  };

  render() {
    const {previewVisible, previewImage, previewTitle, fileList, isChange} = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined/>
        <div style={{marginTop: 8}}>点击上传</div>
      </div>
    );
    const image = fileList[0];
    return (
          <Row className={'image-upload'} justify="space-around" align="middle">
            <Col span={12}>
              <Image width={250} src={isChange?image.thumbUrl:this.props.srcImage}/>
            </Col>
            <Col span={12}>
              <div className={'upload-area'}>
                <Upload
                  listType="picture-card"
                  className="avatar-uploader"
                  fileList={fileList}
                  onChange={this.handleChange}
                  onPreview={this.handlePreview}
                  onRemove={this.handleRemove}
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                >
                  {uploadButton}
                </Upload>
                <Modal
                  visible={previewVisible}
                  title={previewTitle}
                  footer={null}
                  onCancel={this.handleCancel}
                >
                  <img src={previewImage} alt="example"/> :
                </Modal>
              </div>
            </Col>
          </Row>
    )
  }
}

export default ImageUpload